package com.tcm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tcm.entity.Code;
import com.tcm.entity.SocialProject;
import com.tcm.entity.dto.SocialProjectUpdateDto;
import com.tcm.entity.dto.param.SocialProjectPageParam;
import com.tcm.entity.resp.PageR;
import com.tcm.exception.DatabaseOperationException;
import com.tcm.exception.EntityAlreadyExistException;
import com.tcm.mapper.SocialProjectMapper;
import com.tcm.service.CodeService;
import com.tcm.service.SocialProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 社会化项目业务实现类
 * @author Guqier
 * @version 1.0
 * @date 2023/7/23 19:35
 */
@Slf4j
@Service
public class SocialProjectServiceImpl extends ServiceImpl<SocialProjectMapper, SocialProject> implements SocialProjectService {

    @Autowired
    private CodeService codeService;

    @Autowired
    private SocialProjectMapper socialProjectMapper;

    /**
     * 添加社会化项目
     * @param dto 社会化项目信息数据封装参数
     * @param currUserId 当前登录用户ID
     * @return 处理结果，true为成功
     * @throws EntityAlreadyExistException 实体已存在异常
     */
    @Override
    @Transactional
    public boolean addSocialProject(SocialProjectUpdateDto dto, Long currUserId) throws EntityAlreadyExistException {
        // 查询项目编号是否已存在
        LambdaQueryWrapper<SocialProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SocialProject::getNum, dto.getNum());
        if (!this.list(queryWrapper).isEmpty()) {
            throw new EntityAlreadyExistException("项目编号已存在");
        }
        // 插入新项目
        SocialProject socialProject = new SocialProject();
        BeanUtils.copyProperties(dto, socialProject);
        socialProject.setCreateUser(currUserId);
        socialProject.setUpdateUser(currUserId);
        return this.save(socialProject);
    }

    /**
     * 批量删除社会化项目
     * @param ids 社会化项目ID列表
     * @param currUserId 当前登录用户ID
     * @return 删除结果，true为成功。
     */
    @Override
    @Transactional
    public boolean removeSocialProject(List<Long> ids, Long currUserId){
        int cnt = 0;// 用于计数
        for (Long id : ids) {
            SocialProject project = this.getById(id);
            if (project == null) {
                break;
            }
            project.setUpdateUser(currUserId);
            boolean b1 = this.updateById(project);
            boolean b = this.removeById(id);
            if (b1 && b){
                cnt ++;
            }
        }
        if (cnt != ids.size()){
            throw new DatabaseOperationException("数据库操作失败");
        }
        return true;
    }

    /**
     * 修改社会化项目信息
     * @param dto 社会化项目信息数据封装参数
     * @param currUserId 当前登录用户ID
     * @return 处理结果，true为成功
     */
    @Override
    @Transactional
    public boolean modifySocialProject(SocialProjectUpdateDto dto, Long currUserId){
        SocialProject project = this.getById(dto.getId());
        if (project == null){
            return false;
        }
        BeanUtils.copyProperties(dto, project);
        project.setUpdateUser(currUserId);
        return this.updateById(project);
    }

    /**
     * 分页获取社会化项目列表
     * @param param 分页参数
     * @return 社会化项目列表
     */
    @Override
    public PageR<SocialProjectUpdateDto> getSocialProjectListByPage(SocialProjectPageParam param){
        // 构造分页条件
        Page<SocialProject> page = new Page<>(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        PageR<SocialProjectUpdateDto> pageR = new PageR<>();
        LambdaQueryWrapper<SocialProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(param.getNum()), SocialProject::getNum, param.getNum());
        queryWrapper.eq(StringUtils.hasText(param.getName()), SocialProject::getName, param.getName());
        queryWrapper.eq(param.getTypeId() != null, SocialProject::getTypeId, param.getTypeId());

        // 查询分页结果
        this.page(page, queryWrapper);
        // 构造结果集
        BeanUtils.copyProperties(page, pageR, "records");
        pageR.setRecords(page.getRecords().stream().map(socialProject -> {
            SocialProjectUpdateDto dto = new SocialProjectUpdateDto();
            BeanUtils.copyProperties(socialProject, dto);
            Code code = codeService.getById(dto.getTypeId());
            dto.setTypeName(code.getName());
            return dto;
        }).collect(Collectors.toList()));
        return pageR;
    }

    /**
     * 临时忽略逻辑删除获取社会化项目列表
     * @return 社会化项目列表
     */
    @Override
    public List<SocialProject> getSocialProjectListWithoutLogicDelete(){
        return socialProjectMapper.selectAllWithoutLogicDelete();
    }

}
